package com.pingao.mp.api;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pingao.mp.config.jwt.UserLoginToken;
import com.pingao.mp.modular.sys.entity.Menu;
import com.pingao.mp.modular.sys.entity.User;
import com.pingao.mp.modular.sys.mapper.UserMapper;
import com.pingao.mp.modular.sys.service.MenuService;
import com.pingao.mp.modular.sys.service.UserService;
import com.pingao.mp.utils.Constant;
import com.pingao.mp.utils.Md5;
import com.pingao.mp.utils.set.MapBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/sign")
public class SignController {

    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuService menuService;

    @PostMapping("/login")
    public Object login(
            @RequestParam(value = "userName") String userName,
            @RequestParam(value = "password") String password
    ) {
        MapBuilder<String,Object> map = new MapBuilder<>();
        User user = userService.getOne(new QueryWrapper<User>().eq(User.COL_NAME, userName).eq(User.COL_PASSWORD, Md5.md5(password)));
        if (user == null) {
            map.put(Constant.ApiMsg,"登录失败,用户名或密码错误").put(Constant.ApiStatus,false);
        } else {
            map.put("token",userService.getToken(user)).put(Constant.ApiData,user).put(Constant.ApiStatus,true).put(Constant.ApiMsg,"登录成功");
        }
        return map.get();
    }

    @UserLoginToken
    @GetMapping("/test")
    public Object test(
            @RequestParam(value = "name") String name
    ) {
        return new MapBuilder<String,Object>().put(Constant.ApiStatus,true).put(Constant.ApiMsg,"测试token验证：" + name).get();
    }


    @UserLoginToken
    @GetMapping("/menus")
    public Object menus (
            @RequestParam("page") Integer page,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "keyword",required = false) String keyword,
            HttpServletRequest request
    ) {
        Page<Menu> p = new Page<>(page,pageSize);
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        if(keyword != null && !keyword.isEmpty()){
            queryWrapper.and(q->q.like(Menu.COL_MODULE_NAME,keyword).or().like(Menu.COL_ACTION_NAME,keyword).or().like(Menu.COL_FUNCTION_NAME,keyword));
        }
        return menuService.page(p,queryWrapper);
    }
}